package com.yunze.system.service.impl.yunze;


import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.util.MapUtils;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yunze.apiCommon.mapper.mysql.YzCardRouteMapper;
import com.yunze.apiCommon.upstreamAPI.ZhiYuan.ZhiYuanApi;
import com.yunze.apiCommon.utils.Arith;
import com.yunze.apiCommon.utils.InternalApiRequest;
import com.yunze.common.core.domain.AjaxResult;
import com.yunze.common.core.domain.entity.SysDept;
import com.yunze.common.core.domain.entity.SysDictData;
import com.yunze.common.core.domain.entity.SysUser;
import com.yunze.common.core.redis.RedisCache;
import com.yunze.common.mapper.mysql.YzCardFlowMapper;
import com.yunze.common.mapper.mysql.YzCardMapper;
import com.yunze.common.mapper.mysql.YzExecutionTaskMapper;
import com.yunze.common.mapper.mysql.YzOrderMapper;
import com.yunze.common.mapper.mysql.bulk.YzBulkBusinessMapper;
import com.yunze.common.mapper.mysql.bulk.YzSmSBulkBusinessMapper;
import com.yunze.common.mapper.mysql.card.YzCardApiOfferinginfolistMapper;
import com.yunze.common.mapper.mysql.card.YzCardUsageReminderMapper;
import com.yunze.common.mapper.mysql.commodity.YzWxByProductAgentMapper;
import com.yunze.common.utils.ServletUtils;
import com.yunze.common.utils.ip.IpUtils;
import com.yunze.common.utils.yunze.*;
import com.yunze.system.config.LTOtherStatusUtlis;
import com.yunze.system.mapper.mysql.SysDeptMapper;
import com.yunze.system.mapper.mysql.SysDictDataMapper;
import com.yunze.system.mapper.mysql.SysUserMapper;
import com.yunze.system.service.yunze.IYzCardService;
import com.yunze.system.service.yunze.IYzUserService;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * 卡信息 业务实现类
 *
 * @author root
 */
@Service
public class YzCardServiceImpl implements IYzCardService {
    private static final Logger log = LoggerFactory.getLogger(YzCardServiceImpl.class);

    @Resource
    private YzCardMapper yzCardMapper;
    @Autowired
    private SysDeptMapper deptMapper;
    @Autowired
    private SysDictDataMapper dictDataMapper;
    @Autowired
    private SysUserMapper userMapper;
    @Resource
    private YzCardRouteMapper yzCardRouteMapper;
    @Resource
    private IYzUserService iYzUserService;
    @Resource
    private RabbitTemplate rabbitTemplate;
    @Resource
    private RedisCache redisCache;
    @Resource
    private YzWxByProductAgentMapper yzWxByProductAgentMapper;
    @Resource
    private YzCardApiOfferinginfolistMapper yzCardApiOfferinginfolistMapper;
    @Resource
    private YzCardUsageReminderMapper yzCardUsageReminderMapper;
    @Resource
    private YzOrderMapper yzOrderMapper;
    @Resource
    private InternalApiRequest internalApiRequest;
    @Resource
    private CardFlowSyn cardFlowSyn;
    @Resource
    private GetShowStatIdArr getShowStatIdArr;
    @Resource
    private YzBulkBusinessMapper yzBulkBusinessMapper;
    @Resource
    private YzExecutionTaskMapper yzExecutionTaskMapper;
    @Resource
    private YzSmSBulkBusinessMapper yzSmSBulkBusinessMapper;
    @Resource
    private YzCardFlowMapper yzCardFlowMapper;


    @Override
    public Map<String, Object> selMap(Map<String, Object> map) {
        Map<String, Object> omp = new HashMap<String, Object>();
        Integer currenPage = map.get("pageNum") != null ? Integer.parseInt(map.get("pageNum").toString()) : 0;
        Integer pageSize = map.get("pageSize") != null ? Integer.parseInt(map.get("pageSize").toString()) : 10;

        Map<String, Object> CountMap = new HashMap<>();
        boolean is_Internal = false;
        //权限过滤
        boolean load_belong = (boolean) map.get("load_belong");
        String currentUserDeptId = map.get("currentUserDeptId").toString();
        if (load_belong) {
            Map<String, Object> findqueryChildrenAreaInfoMap = new HashMap<>();
            findqueryChildrenAreaInfoMap.put("agent_id", currentUserDeptId);
            String agent_idArrStr = yzCardMapper.queryChildrenAreaInfo(findqueryChildrenAreaInfoMap);
            if (agent_idArrStr != null) {
                String agent_idArr[] = agent_idArrStr.split(",");
                if (agent_idArr != null) {
                    List<String> find_agent_id = new ArrayList<>();
                    for (int i = 0; i < agent_idArr.length; i++) {
                        String f_agent_id = agent_idArr[i] != null && agent_idArr[i].length() > 0 ? agent_idArr[i] : null;
                        if (f_agent_id != null) {
                            find_agent_id.add(f_agent_id);
                        }
                    }
                    if (find_agent_id.size() > 0) {
                        map.put("agent_id", find_agent_id);
                    }
                }
            }
        }
        CountMap.putAll(map);
        CountMap.remove("queryParams");
        if (map.get("agent_id") != null) {
            List<Integer> agent_id = (List<Integer>) map.get("agent_id");
            if (!Different.Is_existence(agent_id, 100)) {
                List<String> user_id = iYzUserService.getUserID(CountMap);
                map.put("user_id", user_id);
                CountMap.put("user_id", user_id);
            } else {
                is_Internal = true;//内部人员 部门是 100 的 可看字段增加
            }
        } else {
            is_Internal = true;//内部人员 部门是 100 的 可看字段增加
        }
        map.put("is_Internal", is_Internal);
        map = getChannelIdArr(map);


        CountMap.put("channel_id", map.get("channel_id"));
        PageUtil pu = null;
        List<Map<String, Object>> Rlist = null;
        boolean selLianTong = (boolean) map.get("selLianTong");

        Integer rowCount = null;
        if (selLianTong) {
            rowCount = yzCardMapper.selMapLianTongCount(CountMap);
        } else {
            rowCount = yzCardMapper.selMapCount(CountMap);
        }
      /*
        //同查询条件 缓存 查询总数 120 S
        Object isExecute = redisCache.getCacheObject(JSON.toJSONString(CountMap));
        if (isExecute == null) {
            if (selLianTong) {
                rowCount = yzCardMapper.selMapLianTongCount(CountMap);
            } else {
                rowCount = yzCardMapper.selMapCount(CountMap);
            }
            //redis 存储
            redisCache.setCacheObject(JSON.toJSONString(CountMap), rowCount, 120, TimeUnit.SECONDS);//120 秒缓存
        } else {
            rowCount = Integer.parseInt(isExecute.toString());
        }*/

        rowCount = rowCount != null ? rowCount : 0;
        pu = new PageUtil(rowCount, currenPage, pageSize);//初始化分页工具类
        map.put("StarRow", pu.getStarRow());
        map.put("PageSize", pu.getPageSize());
        if (selLianTong) {
            Rlist = yzCardMapper.selMapLianTong(map);
        } else {
            Rlist = yzCardMapper.selMap(map);
        }
        //数据打包'
        omp.put("Pu", pu);
        omp.put("Data", Rlist);
        omp.put("Pmap", map);
        omp.put("is_Internal", is_Internal);
        System.out.println(omp);
        return omp;

    }

    @Override
    public Map<String, Object> find(Map<String, Object> map) {
        Map<String, Object> findMap = yzCardMapper.find(map);
        if (findMap == null) {
            findMap = yzCardMapper.findNotRoute(map);
        } else {
            Map<String, Object> openSelCardMap = new HashMap<>();
            openSelCardMap.put("config_key", "NotRepeatingSyn");
            String NotRepeatingSyn = yzWxByProductAgentMapper.findConfig(openSelCardMap);
            NotRepeatingSyn = NotRepeatingSyn != null && NotRepeatingSyn.length() > 0 ? NotRepeatingSyn : "5";//默认 5 分钟内不重复同步
            Integer allowTime = Integer.parseInt(NotRepeatingSyn);
            SynCardXTime(findMap, map, allowTime);
        }
        return findMap;
    }


    /**
     * 同步 卡信息和生命周期
     *
     * @param findMap
     * @param map
     * @param allowTime
     */
    public void SynCardXTime(Map<String, Object> findMap, Map<String, Object> map, Integer allowTime) {
        try {
            //判断当前卡号 同步 用量时间 和 生命周期时间 是否超过系统指定配置 时间 X分钟
            String flowTime = findMap.get("flowTime") != null ? findMap.get("flowTime").toString() : null;
            String stateTime = findMap.get("stateTime") != null ? findMap.get("stateTime").toString() : null;


            boolean synFBool = false, synSBool = false;
            if (flowTime != null && flowTime.length() > 8) {
                if (!VeDate.compareTime(flowTime, allowTime)) {
                    synFBool = true;
                }
            } else {
                synFBool = true;
            }
            if (stateTime != null && stateTime.length() > 8) {
                if (!VeDate.compareTime(stateTime, allowTime)) {
                    synSBool = true;
                }
            } else {
                synSBool = true;
            }
            //获取所属通道信息
            Map<String, Object> Route = yzCardMapper.findRoute(map);
            if (Route != null) {
                String cd_status = Route.get("cd_status").toString();
                if (cd_status != null && cd_status != "" && cd_status.equals("1")) {
                    String msg = JSON.toJSONString(Route);
                    if (synFBool) {
                        //生产任务
                        try {
                            rabbitTemplate.convertAndSend("admin_exchange", "compensate.CardFlow.queue", msg, message -> {
                                // 设置消息过期时间 time 分钟 过期
                                message.getMessageProperties().setExpiration("" + (10 * 1000 * 60));
                                return message;
                            });
                        } catch (Exception e) {
                            System.out.println(e.getMessage());
                        }
                    }
                    if (synSBool) {
                        try {
                            rabbitTemplate.convertAndSend("admin_exchange", "compensate.CardStasus.queue", msg, message -> {
                                // 设置消息过期时间 time 分钟 过期
                                message.getMessageProperties().setExpiration("" + (10 * 1000 * 60));
                                return message;
                            });
                        } catch (Exception e) {
                            System.out.println(e.getMessage());
                        }
                    }
                } else {
                    String statusVal = cd_status.equals("2") ? "已停用" : cd_status.equals("3") ? "已删除" : "状态未知";
                    System.out.println("同步 操作失败！" + " 通道 [" + statusVal + "]");
                }
            }
        } catch (Exception e) {
            System.out.println("  " + e.getMessage());
        }
    }


    @Override
    public String uploadCard(MultipartFile file, boolean updateSupport, SysUser User) throws IOException {
        String filename = file.getOriginalFilename();
        String ReadName = UUID.randomUUID().toString().replace("-", "") + filename;
        String newName = UUID.randomUUID().toString().replace("-", "") + "_CardImport";
        String flieUrlRx = "/upload/uploadCard/";
        ReadName = flieUrlRx + ReadName;
        try {
            /**
             * 获取当前项目的工作路径
             */
            File file2 = new File("");
            String filePath = file2.getCanonicalPath();
            File newFile = new File(filePath + ReadName);
            File Url = new File(filePath + flieUrlRx + "1.txt");//tomcat 生成路径
            Upload.mkdirsmy(Url);
            file.transferTo(newFile);

            //1.创建路由 绑定 生产队列 发送消息
            //导卡 路由队列
            String polling_queueName = "admin_saveCard_queue";
            String polling_routingKey = "admin.saveCard.queue";
            String polling_exchangeName = "admin_exchange";//路由
            try {
                // rabbitMQConfig.creatExchangeQueue(polling_exchangeName, polling_queueName, polling_routingKey, null, null, null, BuiltinExchangeType.DIRECT);
                Map<String, Object> start_type = new HashMap<>();
                start_type.put("type", "importCardData");//启动类型
                start_type.put("filePath", filePath);//项目根目录
                start_type.put("ReadName", ReadName);//上传新文件名
                start_type.put("newName", newName);//输出文件名
                start_type.put("User", User);//登录用户信息
                rabbitTemplate.convertAndSend(polling_exchangeName, polling_routingKey, JSON.toJSONString(start_type), message -> {
                    // 设置消息过期时间 30 分钟 过期
                    message.getMessageProperties().setExpiration("" + (30 * 1000 * 60));
                    return message;
                });
            } catch (Exception e) {
                System.out.println("导入 卡号 失败 " + e.getMessage().toString());
                return ("物联卡管理 导入 操作失败！");
            }
        } catch (Exception e) {
            System.out.println(e);
            return "上传excel异常";
        }

        return "物联卡管理 导入指令 已发送，详细信息请在 【执行日志管理】查询！";
    }

    @Override
    public Map<String, Object> findRoute(Map<String, Object> map) {
        return yzCardMapper.findRoute(map);
    }


    @Override
    public List<Map<String, Object>> getDeptName() {
        return deptMapper.getDeptName();
    }

    @Override
    public String exportData(Map<String, Object> map, SysUser User) {
        boolean load_belong = false;//是否加载所属 企业数据
        Object MapAgent_id = map.get("agent_id");
        //导出时 未选中 当前 企业编号时 且登录 部门不是 总平台 赋值部门
        if (MapAgent_id == null && User.getDeptId() != 100) {
            List<String> agent_idArr = new ArrayList<String>();
            agent_idArr.add("" + User.getDeptId());
            map.put("agent_id", agent_idArr);
            load_belong = true;//默认前端没有选择 企业 信息时 加载所有下属卡号信息
        }
        map.remove("pageNum");
        map.remove("pageSize");
        map = getChannelIdArr(map);
        List<String> outCardIccidArr = null;
        //权限过滤
        if (map.get("agent_id") != null) {
            List<Integer> agent_id = (List<Integer>) map.get("agent_id");
            if (!Different.Is_existence(agent_id, 100)) {
                List<String> user_id = iYzUserService.getUserID(map);
                map.put("user_id", user_id);
            }
        }
        String currentUserDeptId = User.getDeptId().toString();
        if (load_belong) {
            Map<String, Object> findqueryChildrenAreaInfoMap = new HashMap<>();
            findqueryChildrenAreaInfoMap.put("agent_id", currentUserDeptId);
            String agent_idArrStr = yzCardMapper.queryChildrenAreaInfo(findqueryChildrenAreaInfoMap);
            if (agent_idArrStr != null) {
                String agent_idArr[] = agent_idArrStr.split(",");
                if (agent_idArr != null) {
                    List<String> find_agent_id = new ArrayList<>();
                    for (int i = 0; i < agent_idArr.length; i++) {
                        String f_agent_id = agent_idArr[i] != null && agent_idArr[i].length() > 0 ? agent_idArr[i] : null;
                        if (f_agent_id != null) {
                            find_agent_id.add(f_agent_id);
                        }
                    }
                    if (find_agent_id.size() > 0) {
                        map.put("agent_id", find_agent_id);
                    }
                }
            }
        }
        map = getChannelIdArr(map);
        boolean selLianTong = (boolean) map.get("selLianTong");
        if (selLianTong) {
            outCardIccidArr = yzCardMapper.outCardIccidLianTong(map);
        } else {
            outCardIccidArr = yzCardMapper.outCardIccid(map);
        }
        if (outCardIccidArr != null && outCardIccidArr.size() > 0) {
            String create_by = " [ " + User.getDept().getDeptName() + " ] - " + " [ " + User.getUserName() + " ] ";
            String newName = UUID.randomUUID().toString().replace("-", "") + "_CardOut";

            String agent_id = User.getDept().getDeptId().toString();
            String task_name = "-物联卡管理 [导出] ";
            String SaveUrl = "/getcsv/" + newName + ".csv";

            Map<String, Object> task_map = new HashMap<String, Object>();
            task_map.put("auth", create_by);
            task_map.put("task_name", task_name);
            task_map.put("url", SaveUrl);
            task_map.put("agent_id", agent_id);
            task_map.put("type", "1");

            //获取字典信息
            List<SysDictData> stateOptions = dictDataMapper.selectDictDataByType("yunze_card_status_ShowId");//卡状态
            List<SysDictData> card_types = dictDataMapper.selectDictDataByType("yunze_card_card_type");//卡类型
            List<SysDictData> customize_whether = dictDataMapper.selectDictDataByType("yunze_customize_whether");//系统是否
            List<SysDictData> cardConnection_type = dictDataMapper.selectDictDataByType("yz_cardConnection_type");//断开网状态
            List<SysDictData> card_network_type = dictDataMapper.selectDictDataByType("yunze_card_network_type");//卡板网络类型


            //获取 用户信息
            List<Map<String, Object>> userArr = userMapper.find_simple();


            //1.创建路由 绑定 生产队列 发送消息
            //导卡 路由队列
            String polling_queueName = "admin_OutCard_queue";
            String polling_routingKey = "admin_OutCard_queue";
            String polling_exchangeName = "admin_exchange";//路由
            try {
                //rabbitMQConfig.creatExchangeQueue(polling_exchangeName, polling_queueName, polling_routingKey, null, null, null, BuiltinExchangeType.DIRECT);
                Map<String, Object> start_type = new HashMap<>();
                start_type.put("type", "importCardData");//启动类型
                start_type.put("newName", newName);//输出文件名
                start_type.put("task_map", task_map);//
                start_type.put("create_by", create_by);//
                start_type.put("User", User);
                start_type.put("outCardIccidArr", outCardIccidArr);
                start_type.put("userArr", userArr);
                start_type.put("stateOptions", stateOptions);
                start_type.put("card_types", card_types);
                start_type.put("customize_whether", customize_whether);
                start_type.put("cardConnection_type", cardConnection_type);
                start_type.put("card_network_type", card_network_type);
                start_type.put("map", map);

                rabbitTemplate.convertAndSend(polling_exchangeName, polling_routingKey, JSON.toJSONString(start_type), message -> {
                    // 设置消息过期时间 30 分钟 过期
                    message.getMessageProperties().setExpiration("" + (30 * 1000 * 60));
                    return message;
                });
            } catch (Exception e) {
                System.out.println("导入 卡号 失败 " + e.getMessage().toString());
                return "物联卡管理 导入 操作失败！";
            }
        } else {
            return "您当前的筛选的查询条件 未找到数据！导出任务取消！";
        }
        return "已下发执行日志可在【系统管理】》【日志管理】》【执行日志】查看";
    }

    @Override
    public List<String> outCardIccid(Map<String, Object> map) {
        Map<String, Object> CountMap = new HashMap<>();
        CountMap.putAll(map);
        CountMap.remove("pageNum");
        CountMap.remove("pageSize");
        //权限过滤
        List<String> user_id = iYzUserService.getUserID(CountMap);
        map.put("user_id", user_id);
        return yzCardMapper.outCardIccid(map);
    }


    @Override
    public List<String> selId(Map<String, Object> map, boolean selLianTong) {
        Map<String, Object> CountMap = new HashMap<>();
        CountMap.putAll(map);
        CountMap.remove("pageNum");
        CountMap.remove("pageSize");
        //权限过滤
        List<String> user_id = iYzUserService.getUserID(CountMap);
        map.put("user_id", user_id);

        if (selLianTong) {
            return yzCardMapper.selIdLianTong(map);
        } else {
            return yzCardMapper.selId(map);
        }
    }

    @Override
    public boolean updStatusId(Map<String, Object> map) {
        return yzCardMapper.updStatusId(map) > 0;
    }


    @Override
    public String dividCard(Map<String, Object> map) {
        String Message = "";
        map.remove("pageNum");
        map.remove("pageSize");
        map = getChannelIdArr(map);
        //权限过滤
        if (map.get("agent_id") != null) {
            List<Integer> agent_id = (List<Integer>) map.get("agent_id");
            if (!Different.Is_existence(agent_id, 100)) {
                List<String> user_id = iYzUserService.getUserID(map);
                map.put("user_id", user_id);
            }
        }
        boolean selLianTong = (boolean) map.get("selLianTong");
        List<String> dividIdArr = selId(map, selLianTong);

        if (dividIdArr != null && dividIdArr.size() > 0) {
            //1.创建路由 绑定 生产队列 发送消息
            //导卡 路由队列
            String polling_queueName = "admin_DistributeCard_queue";
            String polling_routingKey = "admin.DistributeCard.queue";
            String polling_exchangeName = "admin_exchange";//路由
            try {
                //rabbitMQConfig.creatExchangeQueue(polling_exchangeName, polling_queueName, polling_routingKey, null, null, null, BuiltinExchangeType.DIRECT);
                Map<String, Object> start_type = new HashMap<>();
                start_type.putAll(map);
                start_type.put("type", "DistributeCard");//启动类型
                start_type.put("dividIdArr", dividIdArr);//需要划分的数据
                rabbitTemplate.convertAndSend(polling_exchangeName, polling_routingKey, JSON.toJSONString(start_type), message -> {
                    // 设置消息过期时间 30 分钟 过期
                    message.getMessageProperties().setExpiration("" + (30 * 1000 * 60));
                    return message;
                });
            } catch (Exception e) {
                System.out.println("划卡 失败 " + e.getMessage().toString());
                return ("物联卡管理 划卡 操作失败！");
            }
            Message = "当前筛选条件下需要划分的数据 [ " + dividIdArr.size() + " ] 条 至 [ " + map.get("set_dept_name") + " ] [ " + map.get("set_user_name") + " ] 指令已下发详情查看 【执行日志管理】 ！";
        } else {
            Message = "当前筛选条件下未找到需要划分的数据！请核对后重试！";
        }
        return Message;
    }


    /**
     * 获取 运营商类型 的通道id
     *
     * @param map
     * @return
     */
    private Map<String, Object> getChannelIdArr(Map<String, Object> map) {
        //判断是否选择 运营商类型
        map.put("selLianTong", false);

        if (map.get("cd_operator_type") != null) {
            List<String> cd_operator_type = (List<String>) map.get("cd_operator_type");
            if (cd_operator_type.size() > 0) {
                List<Map<String, Object>> smap = yzCardRouteMapper.find_simpleOperatorArr(map);
                //添加 【符合 运营类型】 的 通道 查询条件
                List<String> channel_id = new ArrayList<String>();

                if (map.get("channel_id") != null) {
                    List<String> Channel = (List<String>) map.get("channel_id");
                    channel_id.addAll(Channel);
                }

                if (smap != null && smap.size() > 0) {
                    for (int i = 0; i < smap.size(); i++) {
                        channel_id.add(smap.get(i).get("cd_id").toString());
                    }
                }
                //未找到相匹配的通道时 将 通道id传参 -1 使查询不到相对应数据
                if (channel_id.size() == 0) {
                    channel_id.add("-1");
                } else {
                    map.put("channel_id", channel_id);
                }
                //如果是联通的查询 条件 且 条件是 卡号 查询长度大于19 或 起止 条件 是 iccid
                boolean LianTong = false;
                for (int i = 0; i < cd_operator_type.size(); i++) {
                    if (cd_operator_type.get(i).equals("2")) {
                        LianTong = true;
                    }
                }
                if (LianTong) {
                    Object type = map.get("type");
                    Object value = map.get("value");
                    if (value != null && value.toString().length() > 0 && type != null) {
                        map.put("selLianTong", true);
                    }
                    Object StartAndEndtype = map.get("StartAndEndtype");
                    Object StartValue = map.get("StartValue");
                    Object EndValue = map.get("EndValue");
                    if (StartAndEndtype != null && StartAndEndtype.equals("3") && StartValue != null && EndValue != null) {
                        map.put("selLianTong", true);
                    }
                    List<Map<String, Object>> UpArr = (List<Map<String, Object>>) map.get("UpArr");//导入查询
                    if (UpArr != null && UpArr.size() > 0) {
                        map.put("selLianTong", true);
                    }
                }
            }
        }
        return map;
    }


    @Override
    public String importSet(MultipartFile file, Map<String, Object> map) throws IOException {
        String filename = file.getOriginalFilename();
        String ReadName = UUID.randomUUID().toString().replace("-", "") + filename;
        String flieUrlRx = "/upload/importSet/";
        ReadName = flieUrlRx + ReadName;
        try {
            // 获取当前项目的工作路径
            File file2 = new File("");
            String filePath = file2.getCanonicalPath();
            File newFile = new File(filePath + ReadName);
            File Url = new File(filePath + flieUrlRx + "1.txt");//tomcat 生成路径
            Upload.mkdirsmy(Url);
            file.transferTo(newFile);
            //1.创建路由 绑定 生产队列 发送消息
            String addOrder_exchangeName = "admin_exchange", addOrder_queueName = "admin_CardImportSet_queue", addOrder_routingKey = "admin.CardImportSet.queue",
                    addOrder_del_exchangeName = "dlx_" + addOrder_exchangeName, addOrder_del_queueName = "dlx_" + addOrder_queueName, addOrder_del_routingKey = "dlx_" + addOrder_routingKey;
            try {
                //rabbitMQConfig.creatExchangeQueue(addOrder_exchangeName, addOrder_queueName, addOrder_routingKey, addOrder_del_exchangeName, addOrder_del_queueName, addOrder_del_routingKey, null);
                Map<String, Object> start_type = new HashMap<>();
                start_type.put("filePath", filePath);//项目根目录
                start_type.put("ReadName", ReadName);//上传新文件名
                start_type.put("map", map);//参数
                rabbitTemplate.convertAndSend(addOrder_exchangeName, addOrder_routingKey, JSON.toJSONString(start_type), message -> {
                    // 设置消息过期时间 60 分钟 过期
                    message.getMessageProperties().setExpiration("" + (60 * 1000 * 60));
                    return message;
                });
            } catch (Exception e) {
                System.out.println("连接设置 生产指令  失败 " + e.getMessage().toString());
                return ("连接设置 生产指令 操作失败！");
            }
        } catch (Exception e) {
            System.out.println(e);
            return "上传excel异常";
        }
        return "连接设置 指令 已发送，连接设置详细信息请在 【执行日志管理】查询！";
    }


    @Override
    public String importSelImei(MultipartFile file, Map<String, Object> map) throws IOException {
        String filename = file.getOriginalFilename();
        String ReadName = UUID.randomUUID().toString().replace("-", "") + filename;
        String flieUrlRx = "/upload/importSelImei/";
        ReadName = flieUrlRx + ReadName;
        try {
            // 获取当前项目的工作路径
            File file2 = new File("");
            String filePath = file2.getCanonicalPath();
            File newFile = new File(filePath + ReadName);
            File Url = new File(filePath + flieUrlRx + "1.txt");//tomcat 生成路径
            Upload.mkdirsmy(Url);
            file.transferTo(newFile);


            String agent_id = map.get("agent_id").toString();
            //新增批量执行表
            Map<String, Object> bulkMap = new HashMap<>();
            String task_name = "【查询IMEI】";
            String code = VeDate.getNo(8);
            SysUser User = (SysUser) map.get("User");//登录用户信息
            SysDept Dept = User.getDept();
            String create_by = " [ " + Dept.getDeptName() + " ] - " + " [ " + User.getUserName() + " ] ";
            bulkMap.put("code", code);
            bulkMap.put("task_name", task_name);
            bulkMap.put("auth", create_by);
            bulkMap.put("agent_id", agent_id);
            bulkMap.put("type", "9");//查询IMEI 9
            yzBulkBusinessMapper.add(bulkMap);


            //1.创建路由 绑定 生产队列 发送消息
            String addOrder_exchangeName = "admin_exchange", addOrder_queueName = "admin_CardImportSelImei_queue", addOrder_routingKey = "admin.CardImportSelImei.queue",
                    addOrder_del_exchangeName = "dlx_" + addOrder_exchangeName, addOrder_del_queueName = "dlx_" + addOrder_queueName, addOrder_del_routingKey = "dlx_" + addOrder_routingKey;
            try {
                //rabbitMQConfig.creatExchangeQueue(addOrder_exchangeName, addOrder_queueName, addOrder_routingKey, addOrder_del_exchangeName, addOrder_del_queueName, addOrder_del_routingKey, null);
                Map<String, Object> start_type = new HashMap<>();
                start_type.put("filePath", filePath);//项目根目录
                start_type.put("ReadName", ReadName);//上传新文件名
                start_type.put("bulkMap", bulkMap);//批量任务主表 信息
                start_type.put("map", map);//参数
                rabbitTemplate.convertAndSend(addOrder_exchangeName, addOrder_routingKey, JSON.toJSONString(start_type), message -> {
                    // 设置消息过期时间 60 分钟 过期
                    message.getMessageProperties().setExpiration("" + (60 * 1000 * 60));
                    return message;
                });
            } catch (Exception e) {
                System.out.println("特殊操作查询IMEI 生产指令  失败 " + e.getMessage().toString());
                return ("特殊操作查询IMEI 生产指令 操作失败！");
            }
        } catch (Exception e) {
            System.out.println(e);
            return "上传excel异常";
        }
        return "特殊操作查询IMEI 指令 已发送，连接设置详细信息请在 【批量业务受理】查询！";
    }

    @Override
    public String status(MultipartFile file, Map<String, Object> map) throws IOException {
        String filename = file.getOriginalFilename();
        String ReadName = UUID.randomUUID().toString().replace("-", "") + filename;
        String flieUrlRx = "/upload/importSelImei/";
        ReadName = flieUrlRx + ReadName;
        try {
            // 获取当前项目的工作路径
            File file2 = new File("");
            String filePath = file2.getCanonicalPath();
            File newFile = new File(filePath + ReadName);
            File Url = new File(filePath + flieUrlRx + "/1.txt");//tomcat 生成路径
            Upload.mkdirsmy(Url);
            file.transferTo(newFile);

            String agent_id = map.get("agent_id").toString();


            String type = "";
            String task_name = "";
            String Is_remind_ratio = map.get("Is_remind_ratio").toString();

            String Switch_network = map.get("Switch_network").toString();

            if (Is_remind_ratio.equals("3")) {//批量复机 1
                type = "1";
                task_name = "【批量复机】";
            } else if (Is_remind_ratio.equals("2")) {//批量停机 2
                type = "2";
                task_name = "【批量停机】";
            } else if (Switch_network.equals("3")) {//批量开网 4
                type = "4";
                task_name = "【批量开网】";
            } else if (Switch_network.equals("2")) {//批量断网 3
                type = "3";
                task_name = "【批量断网】";
            }


            //新增批量执行表
            Map<String, Object> bulkMap = new HashMap<>();

            String code = VeDate.getNo(8);
            SysUser User = (SysUser) map.get("User");//登录用户信息
            SysDept Dept = User.getDept();
            String create_by = " [ " + Dept.getDeptName() + " ] - " + " [ " + User.getUserName() + " ] ";
            bulkMap.put("code", code);
            bulkMap.put("task_name", task_name);
            bulkMap.put("auth", create_by);
            bulkMap.put("agent_id", agent_id);
            bulkMap.put("type", type);
            yzBulkBusinessMapper.add(bulkMap);


            //1.创建路由 绑定 生产队列 发送消息
            String addOrder_exchangeName = "admin_exchange", addOrder_queueName = "admin_CardImportBatch_queue", addOrder_routingKey = "admin.CardImportBatch.queue",
                    addOrder_del_exchangeName = "dlx_" + addOrder_exchangeName, addOrder_del_queueName = "dlx_" + addOrder_queueName, addOrder_del_routingKey = "dlx_" + addOrder_routingKey;
            try {
                // rabbitMQConfig.creatExchangeQueue(addOrder_exchangeName, addOrder_queueName, addOrder_routingKey, addOrder_del_exchangeName, addOrder_del_queueName, addOrder_del_routingKey, null);
                Map<String, Object> start_type = new HashMap<>();
                start_type.put("filePath", filePath);//项目根目录
                start_type.put("ReadName", ReadName);//上传新文件名
                start_type.put("bulkMap", bulkMap);//批量任务主表 信息
                start_type.put("map", map);//参数
                rabbitTemplate.convertAndSend(addOrder_exchangeName, addOrder_routingKey, JSON.toJSONString(start_type), message -> {
                    // 设置消息过期时间 60 分钟 过期
                    message.getMessageProperties().setExpiration("" + (60 * 1000 * 60));
                    return message;
                });
            } catch (Exception e) {
                System.out.println("批量停复机、断开网 生产指令  失败 " + e.getMessage().toString());
                return ("批量停复机、断开网 生产指令 操作失败！");
            }
        } catch (Exception e) {
            System.out.println(e);
            return "上传excel异常";
        }
        return "批量停复机、断开网 指令 已发送，连接设置详细信息请在 【批量业务受理】查询！";
    }


    @Override
    public Map<String, Object> CardNumberImport(MultipartFile file, Map<String, Object> map) throws IOException {
        String filename = file.getOriginalFilename();
        String ReadName = UUID.randomUUID().toString().replace("-", "") + filename;
        String flieUrlRx = "/upload/cardNumber/";
        ReadName = flieUrlRx + ReadName;
        try {
            // 获取当前项目的工作路径
            File file2 = new File("");
            String filePath = file2.getCanonicalPath();
            File newFile = new File(filePath + ReadName);
            File Url = new File(filePath + flieUrlRx + "1.txt");//tomcat 生成路径
            Upload.mkdirsmy(Url);
            file.transferTo(newFile);
            ExcelConfig excelConfig = new ExcelConfig();
            String columns[] = {"cardNumber"};
            List<Map<String, Object>> list = excelConfig.getExcelListMap(filePath + ReadName, columns);
            //System.out.println(list.toString());
            //System.out.println(list);
            map.put("UpArr", list);
        } catch (Exception e) {
            System.out.println(e);
        }
        return selMap(map);
    }


    @Override
    public String importSetCardInfo(MultipartFile file, Map<String, Object> map) throws IOException {
        String filename = file.getOriginalFilename();
        String ReadName = UUID.randomUUID().toString().replace("-", "") + filename;
        String flieUrlRx = "/upload/importSetCardInfo/";
        ReadName = flieUrlRx + ReadName;
        try {
            // 获取当前项目的工作路径
            File file2 = new File("");
            String filePath = file2.getCanonicalPath();
            File newFile = new File(filePath + ReadName);
            File Url = new File(filePath + flieUrlRx + "1.txt");//tomcat 生成路径
            Upload.mkdirsmy(Url);
            file.transferTo(newFile);
            //1.创建路由 绑定 生产队列 发送消息
            String addOrder_exchangeName = "admin_exchange", addOrder_queueName = "admin_importSetCardInfo_queue", addOrder_routingKey = "admin.importSetCardInfo.queue",
                    addOrder_del_exchangeName = "dlx_" + addOrder_exchangeName, addOrder_del_queueName = "dlx_" + addOrder_queueName, addOrder_del_routingKey = "dlx_" + addOrder_routingKey;
            try {
                // rabbitMQConfig.creatExchangeQueue(addOrder_exchangeName, addOrder_queueName, addOrder_routingKey, addOrder_del_exchangeName, addOrder_del_queueName, addOrder_del_routingKey, null);
                Map<String, Object> start_type = new HashMap<>();
                start_type.put("filePath", filePath);//项目根目录
                start_type.put("ReadName", ReadName);//上传新文件名
                start_type.put("map", map);//参数
                rabbitTemplate.convertAndSend(addOrder_exchangeName, addOrder_routingKey, JSON.toJSONString(start_type), message -> {
                    // 设置消息过期时间 60 分钟 过期
                    message.getMessageProperties().setExpiration("" + (60 * 1000 * 60));
                    return message;
                });
            } catch (Exception e) {
                System.out.println("特殊操作变更卡分组、备注 生产指令  失败 " + e.getMessage().toString());
                return ("特殊操作变更卡分组、备注 生产指令 操作失败！");
            }
        } catch (Exception e) {
            System.out.println(e);
            return "上传excel异常";
        }
        return "特殊操作变更卡分组、备注 指令 已发送，连接设置详细信息请在 【执行日志管理】查询！";
    }

    @Override
    public List<String> getCardGrouping(Map<String, Object> map) {
        //查询所属下 分组
        if (map.get("agent_id") != null) {
            map.put("agent_id", yzCardMapper.queryChildrenAreaInfo(map));
        }

        return yzCardMapper.getCardGrouping(map);
    }

    @Override
    public boolean updActivate(Map<String, Object> map) {
        return yzCardMapper.updActivate(map) > 0;
    }


    @Override
    public boolean UpdateFill(Map<String, Object> map) {
        return yzCardMapper.UpdateFill(map) > 0;
    }

    /***停机*/
    @Override
    public String stoppedarr(Map<String, Object> map) {
        //1.创建路由 绑定 生产队列 发送消息
        String addOrder_exchangeName = "admin_exchange", addOrder_queueName = "admin_Stopped_queue", addOrder_routingKey = "admin.Stopped.queue",
                addOrder_del_exchangeName = "dlx_" + addOrder_exchangeName, addOrder_del_queueName = "dlx_" + addOrder_queueName, addOrder_del_routingKey = "dlx_" + addOrder_routingKey;
        try {
            Map<String, Object> start_type = new HashMap<>();
            start_type.put("map", map);//参数
            rabbitTemplate.convertAndSend(addOrder_exchangeName, addOrder_routingKey, JSON.toJSONString(start_type), message -> {
                // 设置消息过期时间 60 分钟 过期
                message.getMessageProperties().setExpiration("" + (60 * 1000 * 60));
                return message;
            });
        } catch (Exception e) {
            System.out.println("批量 【停机】 生产指令  失败 " + e.getMessage().toString());
            return ("批量 【停机】 生产指令 操作失败！");
        }

        return "批量 【停机】 指令 已发送，连接设置详细信息请在 【执行日志管理】查询！";
    }

    /***复机*/
    @Override
    public String machinearr(Map<String, Object> map) {
        //1.创建路由 绑定 生产队列 发送消息
        String addOrder_exchangeName = "admin_exchange", addOrder_queueName = "admin_Machine_queue", addOrder_routingKey = "admin.Machine.queue",
                addOrder_del_exchangeName = "dlx_" + addOrder_exchangeName, addOrder_del_queueName = "dlx_" + addOrder_queueName, addOrder_del_routingKey = "dlx_" + addOrder_routingKey;
        try {
            Map<String, Object> start_type = new HashMap<>();
            start_type.put("map", map);//参数
            rabbitTemplate.convertAndSend(addOrder_exchangeName, addOrder_routingKey, JSON.toJSONString(start_type), message -> {
                // 设置消息过期时间 60 分钟 过期
                message.getMessageProperties().setExpiration("" + (60 * 1000 * 60));
                return message;
            });
        } catch (Exception e) {
            System.out.println("批量 【复机】 生产指令  失败 " + e.getMessage().toString());
            return ("批量 【复机】 生产指令 操作失败！");
        }

        return "批量 【复机】 指令 已发送，连接设置详细信息请在 【执行日志管理】查询！";
    }

    /***断网*/
    @Override
    public String disconnectNetworkarr(Map<String, Object> map) {
        //1.创建路由 绑定 生产队列 发送消息
        String addOrder_exchangeName = "admin_exchange", addOrder_queueName = "admin_DisconnectNetwork_queue", addOrder_routingKey = "admin.DisconnectNetwork.queue",
                addOrder_del_exchangeName = "dlx_" + addOrder_exchangeName, addOrder_del_queueName = "dlx_" + addOrder_queueName, addOrder_del_routingKey = "dlx_" + addOrder_routingKey;
        try {
            Map<String, Object> start_type = new HashMap<>();
            start_type.put("map", map);//参数
            rabbitTemplate.convertAndSend(addOrder_exchangeName, addOrder_routingKey, JSON.toJSONString(start_type), message -> {
                // 设置消息过期时间 60 分钟 过期
                message.getMessageProperties().setExpiration("" + (60 * 1000 * 60));
                return message;
            });
        } catch (Exception e) {
            System.out.println("批量 【断网】 生产指令  失败 " + e.getMessage().toString());
            return ("批量 【断网】 生产指令 操作失败！");
        }

        return "批量 【断网】 指令 已发送，连接设置详细信息请在 【执行日志管理】查询！";
    }

    /***开网*/
    @Override
    public String openNetworkarr(Map<String, Object> map) {
        //1.创建路由 绑定 生产队列 发送消息
        String addOrder_exchangeName = "admin_exchange", addOrder_queueName = "admin_OpenNetwork_queue", addOrder_routingKey = "admin.OpenNetwork.queue",
                addOrder_del_exchangeName = "dlx_" + addOrder_exchangeName, addOrder_del_queueName = "dlx_" + addOrder_queueName, addOrder_del_routingKey = "dlx_" + addOrder_routingKey;
        try {
            Map<String, Object> start_type = new HashMap<>();
            start_type.put("map", map);//参数
            rabbitTemplate.convertAndSend(addOrder_exchangeName, addOrder_routingKey, JSON.toJSONString(start_type), message -> {
                // 设置消息过期时间 60 分钟 过期
                message.getMessageProperties().setExpiration("" + (60 * 1000 * 60));
                return message;
            });
        } catch (Exception e) {
            System.out.println("批量 【开网】 生产指令  失败 " + e.getMessage().toString());
            return ("批量 【开网】 生产指令 操作失败！");
        }

        return "批量 【开网】 指令 已发送，连接设置详细信息请在 【执行日志管理】查询！";
    }

    /**
     * 批量同步用量
     */
    @Override
    public String consumptionarr(Map<String, Object> map) {
        //1.创建路由 绑定 生产队列 发送消息
        String addOrder_exchangeName = "admin_exchange", addOrder_queueName = "admin_Consumption_queue", addOrder_routingKey = "admin.Consumption.queue",
                addOrder_del_exchangeName = "dlx_" + addOrder_exchangeName, addOrder_del_queueName = "dlx_" + addOrder_queueName, addOrder_del_routingKey = "dlx_" + addOrder_routingKey;
        try {
            Map<String, Object> start_type = new HashMap<>();
            start_type.put("map", map);//参数
            rabbitTemplate.convertAndSend(addOrder_exchangeName, addOrder_routingKey, JSON.toJSONString(start_type), message -> {
                // 设置消息过期时间 60 分钟 过期
                message.getMessageProperties().setExpiration("" + (60 * 1000 * 60));
                return message;
            });
        } catch (Exception e) {
            System.out.println("批量 【同步用量】 生产指令  失败 " + e.getMessage().toString());
            return ("批量 【同步用量】 生产指令 操作失败！");
        }

        return "批量 【同步用量】 指令 已发送，连接设置详细信息请在 【执行日志管理】查询！";
    }

    /**
     * 批量同步状态
     */
    @Override
    public String publicmethodarr(Map<String, Object> map) {
        //1.创建路由 绑定 生产队列 发送消息
        String addOrder_exchangeName = "admin_exchange", addOrder_queueName = "admin_PublicMethod_queue", addOrder_routingKey = "admin.PublicMethod.queue",
                addOrder_del_exchangeName = "dlx_" + addOrder_exchangeName, addOrder_del_queueName = "dlx_" + addOrder_queueName, addOrder_del_routingKey = "dlx_" + addOrder_routingKey;
        try {
            Map<String, Object> start_type = new HashMap<>();
            start_type.put("map", map);//参数
            rabbitTemplate.convertAndSend(addOrder_exchangeName, addOrder_routingKey, JSON.toJSONString(start_type), message -> {
                // 设置消息过期时间 60 分钟 过期
                message.getMessageProperties().setExpiration("" + (60 * 1000 * 60));
                return message;
            });
        } catch (Exception e) {
            System.out.println("批量 【同步状态】 生产指令  失败 " + e.getMessage().toString());
            return ("批量 【同步状态】 生产指令 操作失败！");
        }

        return "批量 【同步状态】 指令 已发送，连接设置详细信息请在 【执行日志管理】查询！";
    }

    /**
     * 批量 【同步状态和用量】
     */
    @Override
    public String consumptionandstatearr(Map<String, Object> map) {
        //1.创建路由 绑定 生产队列 发送消息
        String addOrder_exchangeName = "admin_exchange", addOrder_queueName = "admin_ConsumptionAndState_queue", addOrder_routingKey = "admin.ConsumptionAndState.queue",
                addOrder_del_exchangeName = "dlx_" + addOrder_exchangeName, addOrder_del_queueName = "dlx_" + addOrder_queueName, addOrder_del_routingKey = "dlx_" + addOrder_routingKey;
        try {
            Map<String, Object> start_type = new HashMap<>();
            start_type.put("map", map);//参数
            rabbitTemplate.convertAndSend(addOrder_exchangeName, addOrder_routingKey, JSON.toJSONString(start_type), message -> {
                // 设置消息过期时间 60 分钟 过期
                message.getMessageProperties().setExpiration("" + (60 * 1000 * 60));
                return message;
            });
        } catch (Exception e) {
            System.out.println("批量 【同步状态和用量】 生产指令  失败 " + e.getMessage().toString());
            return ("批量 【同步状态和用量】 生产指令 操作失败！");
        }

        return "批量 【同步状态和用量】 指令 已发送，连接设置详细信息请在 【执行日志管理】查询！";
    }

    @Override
    public Map<String, Object> getIccid(Map<String, Object> map) {
        Map<String, Object> Rmap = null;
        List<Map<String, Object>> selVidArr = yzCardMapper.selVid(map);
        if (selVidArr != null && selVidArr.size() > 0) {
            Rmap = selVidArr.get(0);
            boolean is_Internal = false;
            //权限过滤
            if (map.get("agent_id") != null) {
                List<Integer> agent_id = (List<Integer>) map.get("agent_id");
                if (!Different.Is_existence(agent_id, 100)) {
                } else {
                    is_Internal = true;//内部人员 部门是 100 的 可看字段增加
                }
            } else {
                is_Internal = true;//内部人员 部门是 100 的 可看字段增加
            }
            Rmap.put("is_Internal", is_Internal);
        }
        return Rmap;
    }

    @Override
    public String cancelrealname(MultipartFile file, Map<String, Object> map) throws IOException {
        String filename = file.getOriginalFilename();
        String ReadName = UUID.randomUUID().toString().replace("-", "") + filename;
        String flieUrlRx = "/upload/cancelrealname/";
        ReadName = flieUrlRx + ReadName;

        try {
            // 获取当前项目的工作路径
            File file2 = new File("");
            String filePath = file2.getCanonicalPath();
            File newFile = new File(filePath + ReadName);
            File Url = new File(filePath + flieUrlRx + "1.txt");//tomcat 生成路径
            Upload.mkdirsmy(Url);
            file.transferTo(newFile);

            //新增批量执行表
            String agent_id = map.get("agent_id").toString();
            Map<String, Object> bulkMap = new HashMap<>();
            String task_name = "【取消实名】";
            String code = VeDate.getNo(8);
            SysUser User = (SysUser) map.get("User");//登录用户信息
            SysDept Dept = User.getDept();
            String create_by = " [ " + Dept.getDeptName() + " ] - " + " [ " + User.getUserName() + " ] ";
            bulkMap.put("code", code);
            bulkMap.put("task_name", task_name);
            bulkMap.put("auth", create_by);
            bulkMap.put("agent_id", agent_id);
            bulkMap.put("type", "8");//取消实名 8
            yzBulkBusinessMapper.add(bulkMap);

            //1.创建路由 绑定 生产队列 发送消息
            String addOrder_exchangeName = "admin_exchange", addOrder_queueName = "admin_CardCancelrealname_queue", addOrder_routingKey = "admin.CardCancelrealname.queue",
                    addOrder_del_exchangeName = "dlx_" + addOrder_exchangeName, addOrder_del_queueName = "dlx_" + addOrder_queueName, addOrder_del_routingKey = "dlx_" + addOrder_routingKey;
            try {
                // rabbitMQConfig.creatExchangeQueue(addOrder_exchangeName, addOrder_queueName, addOrder_routingKey, addOrder_del_exchangeName, addOrder_del_queueName, addOrder_del_routingKey, null);
                Map<String, Object> start_type = new HashMap<>();
                start_type.put("filePath", filePath);//项目根目录
                start_type.put("ReadName", ReadName);//上传新文件名
                start_type.put("bulkMap", bulkMap);//批量任务主表 信息
                start_type.put("map", map);//参数
                rabbitTemplate.convertAndSend(addOrder_exchangeName, addOrder_routingKey, JSON.toJSONString(start_type), message -> {
                    // 设置消息过期时间 60 分钟 过期
                    message.getMessageProperties().setExpiration("" + (60 * 1000 * 60));
                    return message;
                });
            } catch (Exception e) {
                System.out.println("批量取消实名 生产指令  失败 " + e.getMessage().toString());
                return ("批量取消实名 生产指令 操作失败！");
            }
        } catch (Exception e) {
            System.out.println(e);
            return "上传excel异常";
        }
        return "批量取消实名 指令 已发送，连接设置详细信息请在 【批量业务受理】查询！";

    }

    @Override
    public Map<String, Object> cardMatch(Map<String, Object> map) {
        Map<String, Object> Rmap = new HashMap<>();
        Map<String, Object> Pmap = new HashMap<>();
        Map<String, Object> cardMatchMap = null;
        String cardNo = map.get("cardNo").toString();
        String PcardNo = map.get("cardNo").toString();

        Integer cardMatchCount = 0;
        Pmap.put("selType", map.get("selType"));

        int frequency = 0;
        while (true) {

            Pmap.put("cardNo", PcardNo);
            cardMatchCount = yzCardMapper.cardMatchCount(Pmap);
            cardMatchCount = cardMatchCount != null ? cardMatchCount : 0;
            if (cardMatchCount > 0) {
                cardMatchMap = yzCardMapper.cardMatchOne(Pmap);
                break;
            } else {
                PcardNo = PcardNo.substring(0, PcardNo.length() - 1);
            }
            frequency += 1;
            if (frequency == 5) {
                break;
            }
        }
        boolean is_Internal = false;
        //权限过滤
        if (map.get("agent_id") != null) {
            List<Integer> agent_id = (List<Integer>) map.get("agent_id");
            if (!Different.Is_existence(agent_id, 100)) {
            } else {
                is_Internal = true;//内部人员 部门是 100 的 可看字段增加
            }
        } else {
            is_Internal = true;//内部人员 部门是 100 的 可看字段增加
        }
        Rmap.put("is_Internal", is_Internal);


        Rmap.put("cardCount", cardMatchCount);
        Rmap.put("cardMatchMap", cardMatchMap);
        Rmap.put("cardPrefix", PcardNo);
        Rmap.put("cardSuffix", cardNo.substring(cardNo.length() - frequency));
        return Rmap;

    }


    @Override
    public String importCardReplace(MultipartFile file, Map<String, Object> map) {
        String filename = file.getOriginalFilename();
        String ReadName = UUID.randomUUID().toString().replace("-", "") + filename;
        String flieUrlRx = "/upload/importCardReplace/";
        ReadName = flieUrlRx + ReadName;
        SysUser User = (SysUser) map.get("User");//登录用户信息
        SysDept Dept = User.getDept();
        String create_by = " [ " + Dept.getDeptName() + " ] - " + " [ " + User.getUserName() + " ] ";
        String task_name = "特殊操作 [批量变更卡信息] ";
        String newName = UUID.randomUUID().toString().replace("-", "") + "_CardInfoReplace";
        String UpdBackupName = UUID.randomUUID().toString().replace("-", "") + "__CardInfoReplaceBackup";//设置分组备注前信息备份名称

        String SaveUrl = "/getcsv/" + newName + ".csv";
        SaveUrl += ",/getcsv/" + UpdBackupName + ".csv";

        Map<String, Object> task_map = new HashMap<String, Object>();
        task_map.put("auth", create_by);
        task_map.put("task_name", task_name);
        task_map.put("url", SaveUrl);
        task_map.put("agent_id", User.getDeptId());
        task_map.put("type", "15");
        yzExecutionTaskMapper.add(task_map);//添加执行 任务表


        try {
            // 获取当前项目的工作路径
            File file2 = new File("");
            String filePath = file2.getCanonicalPath();
            File newFile = new File(filePath + ReadName);
            File Url = new File(filePath + flieUrlRx + "/1.txt");//tomcat 生成路径
            Upload.mkdirsmy(Url);
            file.transferTo(newFile);
            //1.创建路由 绑定 生产队列 发送消息
            String addOrder_exchangeName = "admin_exchange", addOrder_queueName = "admin_CardImportReplace_queue", addOrder_routingKey = "admin.CardImportReplace.queue";
            try {
                Map<String, Object> start_type = new HashMap<>();
                start_type.put("filePath", filePath);//项目根目录
                start_type.put("ReadName", ReadName);//上传新文件名
                start_type.put("map", map);//参数
                start_type.put("task_map", task_map);//参数
                start_type.put("newName", newName);//参数
                start_type.put("UpdBackupName", UpdBackupName);//参数


                rabbitTemplate.convertAndSend(addOrder_exchangeName, addOrder_routingKey, JSON.toJSONString(start_type), message -> {
                    // 设置消息过期时间 60 分钟 过期
                    message.getMessageProperties().setExpiration("" + (60 * 1000 * 60));
                    return message;
                });
            } catch (Exception e) {
                System.out.println("批量更新卡信息 生产指令  失败 " + e.getMessage().toString());
                return ("批量更新卡信息 生产指令 操作失败！");
            }
        } catch (Exception e) {
            System.out.println(e);
            return "上传excel异常";
        }
        return "批量更新卡信息 指令 已发送，更新卡信息 详细信息请在 【执行日志管理】查询！";
    }

    @Override
    public String ChangeF(Map<String, Object> map, SysUser User) {
        String agent_id = "" + User.getDeptId();

        //新增批量执行表
        Map<String, Object> bulkMap = new HashMap<>();
        String task_name = "勾选 -【灵活变更状态】";
        String code = VeDate.getNo(8);
        SysDept Dept = User.getDept();
        String create_by = " [ " + Dept.getDeptName() + " ] - " + " [ " + User.getUserName() + " ] ";
        bulkMap.put("code", code);
        bulkMap.put("task_name", task_name);
        bulkMap.put("auth", create_by);
        bulkMap.put("agent_id", agent_id);
        bulkMap.put("type", "10");//灵活变更状态 10
        yzBulkBusinessMapper.add(bulkMap);


        //1.创建路由 绑定 生产队列 发送消息
        String addOrder_exchangeName = "admin_exchange", addOrder_queueName = "admin_fileFlexible_queue", addOrder_routingKey = "admin.fileFlexible.queue",
                addOrder_del_exchangeName = "dlx_" + addOrder_exchangeName, addOrder_del_queueName = "dlx_" + addOrder_queueName, addOrder_del_routingKey = "dlx_" + addOrder_routingKey;
        try {
            Map<String, Object> start_type = new HashMap<>();
            start_type.put("bulkMap", bulkMap);//批量任务主表 信息
            start_type.put("map", map);//参数
            rabbitTemplate.convertAndSend(addOrder_exchangeName, addOrder_routingKey, JSON.toJSONString(start_type), message -> {
                // 设置消息过期时间 60 分钟 过期
                message.getMessageProperties().setExpiration("" + (60 * 1000 * 60));
                return message;
            });
        } catch (Exception e) {
            System.out.println("批量 【灵活变更状态】 生产指令  失败 " + e.getMessage().toString());
            return ("批量 【灵活变更状态】 生产指令 操作失败！");
        }

        return "批量 【灵活变更状态】 指令 已发送，连接设置详细信息请在 【批量业务受理】查询！";
    }

    @Override
    public Map<String, Object> selCardOpen(String ip, Map<String, Object> map) {
        Map<String, Object> retMap = new HashMap<>();
        List<Map<String, Object>> rList = new ArrayList<>();
        List<String> dList = new ArrayList<>();
        boolean bool = false;
        String Message = "操作取消";

        Integer mCount = 0;
        Integer openSelCardMaxInt = 0;
        Object openSelCardMax = redisCache.getCacheObject("openSelCard.max");
        if (openSelCardMax != null && openSelCardMax.toString().length() > 0) {
            openSelCardMaxInt = Integer.parseInt(openSelCardMax.toString());
        } else {
            Map<String, Object> openSelCardMap = new HashMap<>();
            openSelCardMap.put("config_key", "openSelCard.max");
            String openSelCard_str = yzWxByProductAgentMapper.findConfig(openSelCardMap);
            openSelCard_str = openSelCard_str != null && openSelCard_str.length() > 0 ? openSelCard_str : "5";//默认60秒五次
            openSelCardMaxInt = Integer.parseInt(openSelCard_str);
            redisCache.setCacheObject("openSelCard.max", openSelCard_str, 1, TimeUnit.HOURS);//1 小时 缓存
        }


        Object isExecute = redisCache.getCacheObject(ip);

        if (isExecute != null) {
            mCount = Integer.parseInt(isExecute.toString());
        }

        String rKey = "maxTestPeriodDays";
        Object testPeriodDaysIsExecute = redisCache.getCacheObject(rKey);
        String maxTestPeriodDays = "180";//默认 180 天
        if (testPeriodDaysIsExecute == null) {
            HashMap<String, Object> configMap = new HashMap<>();
            configMap.put("config_key", rKey);
            maxTestPeriodDays = yzWxByProductAgentMapper.findConfig(configMap);// 最大测试期天数
            redisCache.setCacheObject(rKey, maxTestPeriodDays, 3 * 60 * 60, TimeUnit.SECONDS);// 3 小时 【缓存 系统参数】
        } else {
            maxTestPeriodDays = redisCache.getCacheObject(rKey).toString();
        }

        boolean flag = isClose(ip, "selCardOpen", openSelCardMaxInt);
        if (!flag) {
            Map<String, Object> openSelCardMap = new HashMap<>();
            openSelCardMap.put("config_key", "NotRepeatingSyn");
            String NotRepeatingSyn = yzWxByProductAgentMapper.findConfig(openSelCardMap);
            NotRepeatingSyn = NotRepeatingSyn != null && NotRepeatingSyn.length() > 0 ? NotRepeatingSyn : "5";//默认 5 分钟内不重复同步
            Integer allowTime = Integer.parseInt(NotRepeatingSyn);

            List<String> pList = (List<String>) map.get("cardArr");
            for (int i = 0; i < pList.size(); i++) {
                String cardNo = pList.get(i);
                Map<String, Object> pMap = new HashMap<>();
                pMap.put("value", cardNo);
                Map<String, Object> rMap = yzCardMapper.selCardOpen(pMap);
                if (rMap != null && rMap.get("iccid") != null) {
                    String dict_label = rMap.get("dict_label").toString();//卡状态
                    String MaxActivate_date = "";
                    if (dict_label.equals("可测试")) {//判断是否有开卡日期 推演 开卡日期
                        if (rMap.get("open_date") != null && rMap.get("open_date").toString().length() > 0) {
                            String open_date = rMap.get("open_date").toString();//开卡日期
                            MaxActivate_date = VeDate.getBeforeAfterDate(open_date, Integer.parseInt(maxTestPeriodDays));
                        } else {//卡状态 ‘可测试’ 但是 没有开卡日期的 发送获取开卡日期指令
                            Map<String, Object> sendMap = new HashMap<>();
                            sendMap.put("iccid", rMap.get("iccid"));
                            sendMap.put("opType", "open");
                            sendGetOpenDate(sendMap);
                        }
                    }
                    rMap.put("MaxActivate_date", MaxActivate_date);
                    rList.add(rMap);

                    //判断是否需要去 同步 用量 和 生命 周期
                    Map<String, Object> prMap = new HashMap<>();
                    prMap.put("iccid", rMap.get("iccid"));
                    SynCardXTime(rMap, prMap, allowTime);
                } else {
                    dList.add(cardNo);
                }
            }
            bool = true;
        } else {
            Message = "您的查询的频次过于频繁请稍后重试！";
        }
        retMap.put("bool", bool);
        retMap.put("Message", Message);
        retMap.put("rList", rList);
        retMap.put("dList", dList);
        return retMap;
    }


    public boolean isClose(String ip, String method, int times) {
        String key = ip + "_api" + method;
        Long count = redisCache.increment(key, 1);
        if (count == 1) {
            redisCache.expire(key, 60, TimeUnit.SECONDS);
        }
        if (count > times) {
            return true;
        }
        return false;
    }

    @Override
    public List<Map<String, Object>> getListUsage(Map map) {
        return yzCardApiOfferinginfolistMapper.apiIdList(map);
    }

    @Override
    public List<Map<String, Object>> getListReminder(Map map) {
        return yzCardUsageReminderMapper.reminderId(map);
    }

    @Override
    public String CardInfoFlow(Map map) {
        try {
            Map<String, Object> Route = yzCardMapper.findRoute(map);
            if (Route != null) {
                String cd_status = Route.get("cd_status").toString();
                if (cd_status != null && cd_status != "" && cd_status.equals("1")) {
                    Map<String, Object> Rmap = internalApiRequest.queryFlow(map, Route);
                    String code = Rmap.get("code") != null ? Rmap.get("code").toString() : "500";
                    if (code.equals("200")) {
                        //获取 卡用量 开卡日期 更新 card info
                        if (Rmap.get("Use") != null && Rmap.get("Use") != "" && Rmap.get("Use").toString().trim().length() > 0) {
                            Double Use = Double.parseDouble(Rmap.get("Use").toString());
                            if (Use >= 0) {
                                try {
                                    cardFlowSyn.CalculationFlow(map.get("iccid").toString(), Use);
                                } catch (Exception e) {
                                    return ("用量内部计算错误！" + e.getMessage().toString());
                                }
                            } else {
                                return ("接口超频返回暂无数据返回，请稍后重试！");
                            }
                        }
                    } else {
                        return ("网络繁忙稍后重试！" + Rmap.get("Message").toString());
                    }
                    Map<String, Object> newRmap = internalApiRequest.queryCardStatus(map, Route);
                    String newcode = newRmap.get("code") != null ? newRmap.get("code").toString() : "500";
                    if (newcode.equals("200")) {
                        //获取 卡状态 开卡日期 更新 card info
                        if (newRmap.get("statusCode") != null && newRmap.get("statusCode") != "" && newRmap.get("statusCode").toString().trim().length() > 0) {
                            String statusCode = newRmap.get("statusCode").toString().trim();
                            if (!statusCode.equals("0")) {
                                Map<String, Object> Upd_Map = new HashMap<>();
                                Upd_Map.put("status_id", statusCode);
                                Upd_Map.put("status_ShowId", getShowStatIdArr.GetShowStatId(statusCode));
                                Upd_Map.put("iccid", map.get("iccid").toString());
                                try {
                                    yzCardMapper.updStatusId(Upd_Map);//变更卡状态
                                } catch (Exception e) {
                                    return ("DB保存状态操作失败！" + e.getMessage().toString());
                                }
                            } else {
                                return ("接口超频返回暂无数据返回，请稍后重试！");
                            }
                        }
                    } else {
                        return ("网络繁忙稍后重试！" + newRmap.get("Message").toString());
                    }
                    return "同步用量和状态 操作成功";
                } else {
                    String statusVal = cd_status.equals("2") ? "已停用" : cd_status.equals("3") ? "已删除" : "状态未知";
                    return ("同步用量 操作失败！" + " 通道 [" + statusVal + "]");
                }
            } else {
                return (" iccid [" + map.get("iccid") + "] 未划分 API通道 ！请划分通道后重试！");
            }
        } catch (Exception e) {
            String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
            System.out.println("<br/> yunze:card:SynFlow  " + " <br/> ip =  " + ip + " <br/> " + e.getCause().toString());
        }
        return ("单卡同步用量和状态 操作失败！");
    }


    @Override
    public boolean UpdateSingle(Map<String, Object> map) {
        return yzCardMapper.UpdateSingle(map) > 0;
    }


    @Override
    public Map<String, Object> singleState(Map<String, Object> map) {
        Map<String, Object> rMap = new HashMap<>();
        boolean bool = false;
        String message = "单卡灵活变更状态 操作失败";
        Map<String, Object> Route = yzCardMapper.findRoute(map);
        if (Route != null) {
            String cd_status = Route.get("cd_status").toString();
            String iccid = Route.get("iccid").toString();
            Map<String, Object> Obj = new HashMap<>();
            Object ShowId = map.get("status_ShowId");
            Obj.put("operType", ShowId);//API 状态
            Obj.put("iccid", iccid);
            if (cd_status != null && cd_status != "" && cd_status.equals("1")) {
                Map<String, Object> CsFble = internalApiRequest.changeCardStatusFlexible(Obj, Route);
                String code = CsFble.get("code") != null ? CsFble.get("code").toString() : "500";
                if (code.equals("200")) {
                    String statusCode = map.get("status_ShowId").toString();
                    Map<String, Object> Upd_Map = new HashMap<>();
                    Upd_Map.put("status_id", statusCode);
                    Upd_Map.put("status_ShowId", getShowStatIdArr.GetShowStatId(statusCode));
                    Upd_Map.put("iccid", map.get("iccid").toString());
                    try {
                        yzCardMapper.updStatusId(Upd_Map);//变更卡状态
                        bool = true;
                        message = "操作成功！";
                    } catch (Exception e) {
                        message = "DB保存状态操作失败！" + e.getMessage().toString();
                    }
                } else {
                    message = "网络繁忙稍后重试！";
                }
            } else {
                message = "未知状态！";
            }
        } else {
            message = " iccid [" + map.get("iccid") + "] 未划分 API通道 ！请划分通道后重试！";
        }
        rMap.put("bool", bool);
        rMap.put("message", message);
        return rMap;
    }

    @Override
    public List<Map<String, Object>> getOrderCard(Map map) {
        return yzOrderMapper.getOrderCard(map);
    }


    @Override
    public String smsCC(MultipartFile file, Map<String, Object> map) {
        String filename = file.getOriginalFilename();
        String ReadName = UUID.randomUUID().toString().replace("-", "") + filename;
        String flieUrlRx = "/upload/smsCC/";
        ReadName = flieUrlRx + ReadName;

        try {
            // 获取当前项目的工作路径
            File file2 = new File("");
            String filePath = file2.getCanonicalPath();
            File newFile = new File(filePath + ReadName);
            File Url = new File(filePath + flieUrlRx + "1.txt");//tomcat 生成路径
            Upload.mkdirsmy(Url);
            file.transferTo(newFile);

            //新增批量执行表
            String agent_id = map.get("agent_id").toString();
            Map<String, Object> bulkMap = new HashMap<>();
            String task_name = "【批量-短信下发】";
            String code = VeDate.getNo(8);
            SysUser User = (SysUser) map.get("User");//登录用户信息
            SysDept Dept = User.getDept();
            String create_by = " [ " + Dept.getDeptName() + " ] - " + " [ " + User.getUserName() + " ] ";
            bulkMap.put("code", code);
            bulkMap.put("task_name", task_name);
            bulkMap.put("auth", create_by);
            bulkMap.put("agent_id", agent_id);
            bulkMap.put("type", "1");//批量-短信下发
            bulkMap.put("message", map.get("message"));//短信下发内容
            yzSmSBulkBusinessMapper.add(bulkMap);


            //1.创建路由 绑定 生产队列 发送消息
            String addOrder_exchangeName = "admin_exchange", addOrder_queueName = "admin_smsCC_queue", addOrder_routingKey = "admin.smsCC.queue";
            try {
                Map<String, Object> start_type = new HashMap<>();
                start_type.put("filePath", filePath);//项目根目录
                start_type.put("ReadName", ReadName);//上传新文件名
                start_type.put("bulkMap", bulkMap);//批量任务主表 信息
                start_type.put("map", map);//参数
                rabbitTemplate.convertAndSend(addOrder_exchangeName, addOrder_routingKey, JSON.toJSONString(start_type), message -> {
                    // 设置消息过期时间 60 分钟 过期
                    message.getMessageProperties().setExpiration("" + (60 * 1000 * 60));
                    return message;
                });
            } catch (Exception e) {
                System.out.println("批量-短信下发 生产指令  失败 " + e.getMessage());
                return ("批量-短信下发 生产指令 操作失败！");
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return "上传excel异常";
        }
        return "批量-短信下发 指令 已发送，详细信息请在【短信业务受理】查询！";

    }

    @Override
    public Map<String, Object> AsynchronousFlow(Map<String, Object> map) {
        Map<String, Object> rMap = new HashMap<>();
        boolean bool = false;
        String Message = "异步 同步用量 操作失败";
        Map<String, Object> Route = yzCardMapper.findRoute(map);
        if (Route != null) {
            String cd_status = Route.get("cd_status").toString();
            if (cd_status != null && cd_status != "" && cd_status.equals("1")) {
                try {
                    rabbitTemplate.convertAndSend("", "", JSON.toJSONString(map), message -> {
                        // 设置消息过期时间 60 分钟 过期
                        message.getMessageProperties().setExpiration("" + (60 * 1000 * 60));
                        return message;
                    });
                } catch (Exception e) {
                    System.out.println("异步 同步用量 生产指令  失败 " + e.getMessage());
                }
            } else {
                String statusVal = cd_status.equals("2") ? "已停用" : cd_status.equals("3") ? "已删除" : "状态未知";
                Message = "异步 同步用量 操作失败！" + " 通道 [" + statusVal + "]";
            }
        } else {
            Message = " iccid [" + map.get("iccid") + "] 未划分 API通道 ！请划分通道后重试！";
        }
        rMap.put("bool", bool);
        rMap.put("Message", Message);
        return rMap;
    }

    @Override
    public Map<String, Object> AsynchronousStatus(Map<String, Object> map) {
        return null;
    }


    @Override
    public Map<String, Object> SmsCCTextField(Map<String, Object> map) {
        Map<String, Object> rMap = new HashMap<>();
        boolean bool = false;
        String Message = "";
        try {
            //新增批量执行表
            String agent_id = map.get("agent_id").toString();
            Map<String, Object> bulkMap = new HashMap<>();
            String task_name = "【批量-短信下发】";
            String code = VeDate.getNo(8);
            SysUser User = (SysUser) map.get("User");//登录用户信息
            SysDept Dept = User.getDept();
            String create_by = " [ " + Dept.getDeptName() + " ] - " + " [ " + User.getUserName() + " ] ";
            bulkMap.put("code", code);
            bulkMap.put("task_name", task_name);
            bulkMap.put("auth", create_by);
            bulkMap.put("agent_id", agent_id);
            bulkMap.put("type", "1");//批量-短信下发
            bulkMap.put("message", map.get("message"));//短信下发内容
            yzSmSBulkBusinessMapper.add(bulkMap);

            //1.创建路由 绑定 生产队列 发送消息
            String addOrder_exchangeName = "admin_exchange", addOrder_queueName = "admin_smsCCTextField_queue", addOrder_routingKey = "admin.smsCCTextField.queue";
            try {
                Map<String, Object> start_type = new HashMap<>();
                start_type.put("bulkMap", bulkMap);//批量任务主表 信息
                start_type.put("map", map);//参数
                start_type.put("list", map.get("list"));//参数
                rabbitTemplate.convertAndSend(addOrder_exchangeName, addOrder_routingKey, JSON.toJSONString(start_type), message -> {
                    // 设置消息过期时间 60 分钟 过期
                    message.getMessageProperties().setExpiration("" + (60 * 1000 * 60));
                    return message;
                });
                bool = true;
                Message = "操作成功！";
            } catch (Exception e) {
                System.out.println("批量-短信下发 生产指令  失败 " + e.getMessage());
                Message = "批量文本域-短信下发 生产指令  失败！";
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
            Message = "新增批量执行表 失败！！！！";

        }
        rMap.put("bool", bool);
        rMap.put("Message", Message);
        return rMap;
    }

    @Override
    public Map<String, Object> updBalance(Map<String, Object> map) {
        HashMap<String, Object> RMap = new HashMap<>();
        try {
            HashMap<String, Object> insertMap = new HashMap<>();
            String ord_no = VeDate.getNo(8);
            insertMap.put("ord_no", ord_no);
            String ord_type = "9";
            insertMap.put("ord_type", ord_type);
            String ord_name = "人工-余额修改";
            insertMap.put("ord_name", ord_name);
            String iccid = map.get("card").toString();
            insertMap.put("iccid", iccid);
            String wx_ord_no = null;
            insertMap.put("wx_ord_no", wx_ord_no);
            String status = "1";
            insertMap.put("status", status);
            String price = map.get("num").toString();
            insertMap.put("price", price);
            String account = map.get("num").toString();
            insertMap.put("account", account);
            String packet_id = null;
            insertMap.put("packet_id", packet_id);
            String pay_type = "s";
            insertMap.put("pay_type", pay_type);
            String cre_type = "sys";
            insertMap.put("cre_type", cre_type);
            String is_profit = "0";
            insertMap.put("is_profit", is_profit);
            String add_package = "0";
            insertMap.put("add_package", add_package);
            String show_status = "0";
            insertMap.put("show_status", show_status);
            String open_id = null;
            insertMap.put("open_id", open_id);
            String agent_id = map.get("agent_id").toString();
            insertMap.put("agent_id", agent_id);
            String profit_type = "0";
            insertMap.put("profit_type", profit_type);
            String validate_type = null;
            insertMap.put("validate_type", validate_type);
            String info = "余额修改-人工";
            insertMap.put("info", info);
            String add_parameter = null;
            insertMap.put("add_parameter", add_parameter);
            int save = yzOrderMapper.save(insertMap);
            if (save != 0) {
                yzCardMapper.updBalance(map);
            }
            RMap.put("code", 200);
        } catch (Exception e) {
            RMap.put("code", 500);
        }
        return RMap;
    }


    private void sendGetOpenDate(Map map) {
        //1.创建路由 绑定 生产队列 发送消息
        String addOrder_exchangeName = "admin_exchange", addOrder_queueName = "admin_CardGetOpenDate_queue", addOrder_routingKey = "admin.CardGetOpenDate.queue";
        try {
            Map<String, Object> start_type = new HashMap<>();
            start_type.putAll(map);//参数
            rabbitTemplate.convertAndSend(addOrder_exchangeName, addOrder_routingKey, JSON.toJSONString(map), message -> {
                // 设置消息过期时间 60 分钟 过期
                message.getMessageProperties().setExpiration("" + (60 * 1000 * 60));
                return message;
            });
        } catch (Exception e) {
            System.out.println("开放接口发送 ‘获取开卡日期’ 指令 发送  失败 " + e.getMessage().toString());
        }
    }

    public Boolean firstUseTimeMethod(String iccid) {

        try {
            String time = yzCardMapper.selFirstUseTimeByIccid(iccid);
            if (time == null || time == "") {
                Map<String, Object> map = new HashMap<>();
                map.put("iccid", iccid);
                map.put("firstUseTime", VeDate.getStringDate());
                Integer integer = yzCardMapper.insetFirstUseTime(map);
                if (integer == 0) {
                    return false;
                }
                return true;
            } else {
                return false;
            }

        } catch (Exception e) {
            return false;
        }
    }

    @Override
    public Boolean updPwd(Map<String, Object> map) {
        return yzCardMapper.updPwd(map) > 0;
    }

    @Scheduled(cron = "0 0 9  * * ?")
//    @Scheduled(cron = "0 */1 * * * ?")
    public AjaxResult queryAll() {
        //获取联通通道信息
        Map<String, Object> resMap = new HashMap<>();
        resMap.put("cd_id", "86");
        Map<String, Object> routerMapper = yzCardRouteMapper.find(resMap);
        JSONObject object = new JSONObject();
        object.put("operator", "2");
        object.put("pageSize", "9999999");
        object.put("pageNo", "1");
        object.put("method", "sohan.m2m.iccidinfo.quryall");
        object.put("timestamp", System.currentTimeMillis() + "");
        object.put("username", routerMapper.get("cd_username").toString());
        String key = routerMapper.get("cd_pwd").toString();
        String sign = getZYLTSign(object, key);
        object.put("sign", sign);
        try {
            this.HttpClint(object, sign);
        } catch (Exception e) {
            e.getMessage();
            return AjaxResult.error();
        }
        return AjaxResult.success();
    }

    private void HttpClint(JSONObject object, String sign) throws ParseException {
        String post = HttpUtil.post("https://apim2m.iot-sohan.cn/index/m2m/api/v1", object.toString());
        JSONObject resObject = JSONObject.parseObject(post);
        if (resObject.get("errorCode").toString().equals("SUCCESS")) {
            JSONObject jsonObject = JSONObject.parseObject(resObject.get("data").toString());
//            System.err.println(jsonObject.get("iccds"));
            List<Map<String, Object>> maps = (List<Map<String, Object>>) jsonObject.get("iccds");
            for (Map<String, Object> map : maps) {
                //校验新增还是修改
                Integer count = yzCardMapper.findCount(map);
                String cardStatus = map.get("cardStatus").toString();
                Integer resChangeType = LTOtherStatusUtlis.resChangeType(cardStatus);
                if (count > 0) {
                    Map<String, Object> updateMap = new HashMap<>();
                    //大于0走update
                    updateMap.put("status_ShowId", resChangeType);
                    updateMap.put("iccid", map.get("iccid").toString());
                    yzCardMapper.updCardReplaceLT(updateMap);
                } else {
                    Map<String, Object> addMap = new HashMap<>();
                    //等于于0走add
                    addMap.put("status_ShowId", resChangeType);
                    addMap.put("iccid", map.get("iccid").toString());
                    addMap.put("create_by", "[ 总企业 ] -  [ admin ]");
                    if (!map.get("activatedTime").toString().equals("null")) {
                        String activatedTime = map.get("activatedTime").toString();
                        String substring = activatedTime.substring(0, activatedTime.length() - 10);
                        addMap.put("activate_date", substring);
                    }
                    yzCardMapper.insertCardLT(addMap);
                }
            }
        }
    }

    @Override
    public List<Map<String, Object>> findTuJuRoute() {
        return yzCardMapper.findTuJuRoute();
    }

    @Override
    public List<Map<String, Object>> findTuJuCardStatus() {
        return yzCardMapper.findTuJuCardStatus();
    }

    public static String getZYLTSign(Map<String, Object> map, String key) {
        map.remove("sign");
        ArrayList<String> list = new ArrayList<String>();
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            Object value = entry.getValue();
            if (null != value) {
                if (value instanceof List) {
                    list.add(entry.getKey() + "=" + JSON.toJSONString(value) + "&");
                } else {
                    list.add(entry.getKey() + "=" + value.toString() + "&");
                }
            }
        }
        int size = list.size();
        String[] arrayToSort = list.toArray(new String[size]);
        Arrays.sort(arrayToSort, String.CASE_INSENSITIVE_ORDER);
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < size; i++) {
            sb.append(arrayToSort[i]);
        }
        String result = sb.toString();
        log.debug("签名原串：" + result);
        result += "key=" + key;
        return DigestUtils.md5Hex(result).toUpperCase();
    }

    @Scheduled(cron = "0 */10 * * * ?")
    public AjaxResult queryInfoAll() {
        //获取联通通道信息
        Map<String, Object> resMap = new HashMap<>();
        resMap.put("cd_id", "86");
        Map<String, Object> routerMapper = yzCardRouteMapper.find(resMap);
        JSONObject object = new JSONObject();
        List<Map<String, Object>> routerCard = yzCardMapper.findRouterCard(resMap);
        for (Map<String, Object> resRouMap : routerCard) {
            String iccid = resRouMap.get("iccid").toString();
            object.put("iccid", iccid);
            object.put("operator", "2");
            object.put("method", "sohan.m2m.iccidinfo.queryone");
            object.put("timestamp", System.currentTimeMillis() + "");
            object.put("username", routerMapper.get("cd_username").toString());
            String key = routerMapper.get("cd_pwd").toString();
            String sign = getZYLTSign(object, key);
            object.put("sign", sign);
            try {
                double remaining = 0;
                if (resRouMap.containsKey("remaining")) {
                    remaining = Double.parseDouble(resRouMap.get("remaining").toString());
                }
                this.LTCardInfoAll(object, remaining);
            } catch (Exception e) {
                e.getMessage();
                return AjaxResult.error();
            }
        }
        return AjaxResult.success();
    }

    private void LTCardInfoAll(JSONObject object, Double remaining) {
        String post = HttpUtil.post("https://apim2m.iot-sohan.cn/index/m2m/api/v1", object.toString());
        JSONObject resObject = JSONObject.parseObject(post);
        if (resObject.get("errorCode").toString().equals("SUCCESS")) {
            JSONObject jsonObject = JSONObject.parseObject(resObject.get("data").toString());
            String totalUnusedFlow = jsonObject.get("totalUsedFlow").toString();
            String imsi = jsonObject.get("imsi").toString();
            String msisdn = jsonObject.get("msisdn").toString();
            String iccid = jsonObject.get("iccid").toString();
            Map<String, Object> stringObjectMap = yzCardFlowMapper.selDom(iccid);
            double UnusedFlow = Double.parseDouble(totalUnusedFlow);
            String trueFlow = stringObjectMap.get("true_flow").toString();
            double due = Double.parseDouble(trueFlow);
            Map<String, Object> putMap = new HashMap<>();
            if (remaining.toString().equals("0")) {
//                due = remaining - used;
                putMap.put("used", totalUnusedFlow);
                putMap.put("remaining", due - UnusedFlow);
                putMap.put("imsi", imsi);
                putMap.put("msisdn", msisdn);
                putMap.put("iccid", iccid);
                yzCardMapper.updUsed(putMap);
            } else {
                putMap.put("used", totalUnusedFlow);
                putMap.put("remaining", due - UnusedFlow);
                putMap.put("imsi", imsi);
                putMap.put("msisdn", msisdn);
                putMap.put("iccid", iccid);
                yzCardMapper.updUsed(putMap);
            }
//            yzCardMapper.updCardReplaceLT(putMap);
        }

    }

    public AjaxResult queryFirstTotal(String parmas) {
        HashMap<String, Object> Parammap = new HashMap<String, Object>();
        if (parmas != null) {
            parmas = parmas.replace("%2F", "/");//转义 /
        }
        try {
            parmas = AesEncryptUtil.desEncrypt(parmas);
            Parammap.putAll(JSON.parseObject(parmas));
            Map<String, Object> list = deptMapper.getList(parmas);
            return AjaxResult.success(list);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    @Scheduled(cron = "0 */15 * * * ?")
    public void queryZYCardInfoAll() {
        Map<String, Object> putMap = new HashMap<>();
        List<Map<String, Object>> maps = yzCardMapper.selAnHuiApi();
        for (Map<String, Object> map : maps) {
            ZhiYuanApi zhiYuanApi = new ZhiYuanApi(map);
            Map<String, Object> stringObjectMap = zhiYuanApi.marginQuery(map.get("iccid").toString());
            double kb = 0.0;
            double Use = 0.0;
            if (!stringObjectMap.get("code").toString().equals("0")) {
                Use = 0.0;
            } else if (stringObjectMap.get("code").toString().equals("0")) {
                Object resdata = stringObjectMap.get("data");
                Map<String, Object> objectMap = JSONObject.parseObject(resdata.toString());
                kb = Double.parseDouble(objectMap.get("used").toString());
                Use = Arith.formatToTwo(Arith.div(kb, 1024));//KB 转 MB
            }
            putMap.put("used",Use);
            putMap.put("iccid",map.get("iccid").toString());
            yzCardMapper.updNewUsed(putMap);
        }
    }

    @Override
    public boolean updManageStatusId(Map<String, Object> updMap) {
        return yzCardMapper.updManageStatusId(updMap) > 0;
    }

    public Object getMonthListOf2025(HashMap<String, Object> parammap) {
        Integer rowCount = null;
        HashMap<String, Object> CountMap = new HashMap<>();
        CountMap.putAll(parammap);
        CountMap.remove("queryParams");
        rowCount = yzCardMapper.selCountMonthListOf2025(CountMap);
        PageUtil pu = null;
        Integer currenPage = parammap.get("pageNum") != null ? Integer.parseInt(parammap.get("pageNum").toString()) : 0;
        Integer pageSize = parammap.get("pageSize") != null ? Integer.parseInt(parammap.get("pageSize").toString()) : 10;
        Map<String, Object> map = new HashMap<>();
        rowCount = rowCount != null ? rowCount : 0;
        pu = new PageUtil(rowCount, currenPage, pageSize);
        parammap.put("StarRow", pu.getStarRow());
        parammap.put("PageSize", pu.getPageSize());
        List<Map<String, Object>> listAll = new ArrayList<>();
        if("2025".equals(parammap.get("type").toString())){
            listAll = yzCardMapper.getMonthListOf2025(parammap);
        }else if("2024".equals(parammap.get("type").toString())){
            listAll = yzCardMapper.getMonthListOf2024(parammap);
        }
        map.put("Pu", pu);
        map.put("Data", listAll);
        map.put("Pmap", parammap);
        return map;

    }

    public void exportMonthDataOfYear(String Pstr, HttpServletResponse response) throws IOException {
        try {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("月流量报表信息", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

            if (Pstr != null) {
                Pstr = Pstr.replace("%2F", "/");
            }
            try {
                Pstr = AesEncryptUtil.desEncrypt(Pstr);
                JSONObject paramMap = JSON.parseObject(Pstr);
                // 构造表头
                List<List<String>> headers = buildHeaders();
                // 设置内容样式
                WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
                WriteFont contentWriteFont = new WriteFont();
                contentWriteFont.setFontHeightInPoints((short) 11);
                contentWriteFont.setFontName("宋体");
                contentWriteCellStyle.setWriteFont(contentWriteFont);
                // 表头样式
                WriteCellStyle headWriteCellStyle = new WriteCellStyle();
                WriteFont headWriteFont = new WriteFont();
                headWriteFont.setFontHeightInPoints((short) 11);
                headWriteFont.setFontName("宋体");
                headWriteFont.setBold(false);
                headWriteCellStyle.setWriteFont(headWriteFont);
                headWriteCellStyle.setBorderBottom(BorderStyle.NONE);
                headWriteCellStyle.setBorderLeft(BorderStyle.NONE);
                headWriteCellStyle.setBorderRight(BorderStyle.NONE);

                HorizontalCellStyleStrategy styleStrategy = new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);
                // 查询数据库数据
                String startNo = paramMap.get("startNo").toString();
                String endNo = paramMap.get("endNo").toString();
                List<Map<String, Object>> dataList = new ArrayList<>();
                if ("2025".equals(paramMap.get("type"))) {
                    dataList = dataFromDatabase(startNo, endNo);
                }else if("2024".equals(paramMap.get("type"))){
                    dataList = dataFromDatabase2024(startNo, endNo);
                }
                // 构造动态行数据
                List<Map<Integer, Object>> rows = buildRows(dataList);
                // 使用 Map 写法导出 Excel
                EasyExcel.write(response.getOutputStream())
                        .head(headers)
                        .excelType(ExcelTypeEnum.XLSX)
                        .registerWriteHandler(styleStrategy)
                        .sheet("月流量报表")
                        .doWrite(rows);

            } catch (Exception e) {
                response.reset();
                response.setContentType("application/json");
                response.setCharacterEncoding("utf-8");
                Map<String, String> map = MapUtils.newHashMap();
                map.put("status", "failure");
                map.put("message", "下载文件失败：" + e.getMessage());
                response.getWriter().println(JSON.toJSONString(map));
            }
        } catch (Exception e) {
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            Map<String, String> map = MapUtils.newHashMap();
            map.put("status", "failure");
            map.put("message", "下载文件失败：" + e.getMessage());
            response.getWriter().println(JSON.toJSONString(map));
        }

    }

    private List<Map<Integer, Object>> buildRows(List<Map<String, Object>> dataList) {
        List<Map<Integer, Object>> rows = new ArrayList<>();
        for (Map<String, Object> data : dataList) {
            if ((int) data.get("status_ShowId") == 4) {
                data.put("status", "已激活");
            } else if ((int) data.get("status_ShowId") == 1) {
                data.put("status", "库存");
            }
            else if ((int) data.get("status_ShowId") == 2) {
                data.put("status", "可测试");
            }
            else if ((int) data.get("status_ShowId") == 3) {
                data.put("status", "待激活");
            }
            else if ((int) data.get("status_ShowId") == 5) {
                data.put("status", "已停机");
            }
            else if ((int) data.get("status_ShowId") == 6) {
                data.put("status", "预销户");
            }
            else if ((int) data.get("status_ShowId") == 7) {
                data.put("status", "已销户");
            }else {
                data.put("status", "未知");
            }
            Map<Integer, Object> row = new HashMap<>();
            int colIndex = 0;
            row.put(colIndex++, data.get("msisdn"));
            row.put(colIndex++, data.get("iccid"));
            row.put(colIndex++, data.get("imsi"));
            row.put(colIndex++, data.get("status"));
            row.put(colIndex++, data.get("one_flow"));
            row.put(colIndex++, data.get("two_flow"));
            row.put(colIndex++, data.get("three_flow"));
            row.put(colIndex++, data.get("four_flow"));
            row.put(colIndex++, data.get("five_flow"));
            row.put(colIndex++, data.get("six_flow"));
            row.put(colIndex++, data.get("seven_flow"));
            row.put(colIndex++, data.get("eight_flow"));
            row.put(colIndex++, data.get("nine_flow"));
            row.put(colIndex++, data.get("ten_flow"));
            row.put(colIndex++, data.get("eleven_flow"));
            row.put(colIndex++, data.get("twelve_flow"));
            rows.add(row);
        }
        return rows;
    }

    private List<Map<String, Object>> dataFromDatabase2024(String startNo, String endNo) {
        return yzCardMapper.listMonthlyUsageOf2024(startNo, endNo);
    }

    private List<Map<String, Object>> dataFromDatabase(String startNo, String endNo) {
        return yzCardMapper.listMonthlyUsageOfYear(startNo, endNo);
    }

    private List<List<String>> buildHeaders() {
        List<List<String>> headers = new ArrayList<>();
        headers.add(Collections.singletonList("MSISDN"));
        headers.add(Collections.singletonList("ICCID"));
        headers.add(Collections.singletonList("IMSI"));
        headers.add(Collections.singletonList("卡状态"));
        headers.add(Collections.singletonList("1月"));
        headers.add(Collections.singletonList("2月"));
        headers.add(Collections.singletonList("3月"));
        headers.add(Collections.singletonList("4月"));
        headers.add(Collections.singletonList("5月"));
        headers.add(Collections.singletonList("6月"));
        headers.add(Collections.singletonList("7月"));
        headers.add(Collections.singletonList("8月"));
        headers.add(Collections.singletonList("9月"));
        headers.add(Collections.singletonList("10月"));
        headers.add(Collections.singletonList("11月"));
        headers.add(Collections.singletonList("12月"));
        return headers;
    }
}

//    String key = "M25h0BwJxRUp97SET5DCoV0UDO1x2lZx";
//    JSONObject jsonObject = new JSONObject();
//        jsonObject.put("method", "sohan.m2m.iccidinfo.quryall");
//        jsonObject.put("timestamp", System.currentTimeMillis() + "");
//        jsonObject.put("operator","2");
//        jsonObject.put("pageSize","9999999");
//        jsonObject.put("pageNo","1");
//        jsonObject.put("username", "致远");
//    String sign = getSign(jsonObject, key);
//        System.err.println(sign);